#!/bin/zsh

# Describe:     install homebrew
# Create Date： 2021-10-28
# Create Time:  19:08
# Update Date:  2021-10-29
# Update Time:  10:03
# Author:       MiaoCunFa
# Version:      v0.0.4
#
# Usage:        /bin/zsh -c "$(curl -fsSL https://gitee.com/miaocunfa/mac/raw/master/mac_brew.sh)"
#

#===================================================================

download=$HOME/Downloads
homebrew="homebrew-dir-20211028.tgz"
r_md5="6b6a1f63d1730005157912c1c936cbb4"

#-------------------------------------------------------------------

function download()
{
    echo -e "\t开始下载: Homebrew"
    curl -o $download/$homebrew -O http://gjr-soft-repo.oss-cn-qingdao.aliyuncs.com/mac/$homebrew
}

function md5()
{
    echo -e "\t检测到本地已经存在安装包: $download/$homebrew"
    echo -e "\t对本地安装包进行md5校验: "
    echo -e "\t远端 md5值为: $r_md5"

    l_md5=$(/sbin/md5 $download/$homebrew | awk '{print $4}')
    echo -e "\t本地 md5值为: $l_md5"

    if [ "$r_md5" = "$l_md5" ]
    then
        echo -e "\t本地下载包与远端一致, 继续处理"
    else
        echo -e "\t本地下载包与远端不一致, 删除本地包"
        rm -f $download/$homebrew

        echo -e "\t重新下载: Homebrew"
        download
    fi
}

#-------------------------------------------------------------------
# homebrew

if [ ! -f "$download/$homebrew" ]
then
    echo "1"
    download
else
    md5
fi

echo
echo -e "\t开始安装: Homebrew"

if [ -d "/opt/homebrew" ]
then
    echo -e "\t备份旧homebrew"
    echo -e "\t请输入密码 以在/opt目录操作"
    cd /opt; sudo mv homebrew{,.old}
fi

echo -e "\t请输入密码 以在/opt目录解压homebrew"
cd $download
sudo tar -zxf $homebrew -C /opt

echo 'eval "$(/opt/homebrew/bin/brew shellenv)"' >> $HOME/.zprofile
eval "$(/opt/homebrew/bin/brew shellenv)"

echo
echo -e "\tHomebrew 安装已完成"
echo -e "\t输入brew 命令开始查看吧!"

